package email;

import email.EmailDao;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * Created by miaoyu on 2017/7/12.
 */
public class EmailDaoImpl implements EmailDao {
    private static final String host = "smtp.163.com";
    private static final String home_address = "qingdao1997.ko@163.com";
    private static final String password = "19973636qingdao";

    private static MimeBodyPart createContent(String data)
            throws Exception{

        MimeBodyPart contentBody = new MimeBodyPart();
        MimeMultipart contentMulti = new MimeMultipart("related");

        //the textpart
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(data,"text/html");
        contentMulti.addBodyPart(textPart);



        contentBody.setContent(contentMulti);
        return contentBody;
    }

    public boolean sendEmail(String address,String content){
        Properties props = System.getProperties();
        props.put("mail.smtp.host",host);
        props.put("mail.smtp.auth","true");
     /*   Session session = Session.getDefaultInstance(props, new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(home_address,password);
            }
        });*/
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address,password);
            }
        });
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(address));
            message.setSubject("Find Back Your Password");

            MimeBodyPart contentpart = createContent(content);

            MimeMultipart allPart = new MimeMultipart("mixed");
            allPart.addBodyPart(contentpart);
            message.setContent(allPart);
            message.saveChanges();

            // message.setText("Do you recieved my email? Please reply yes/no");
            Transport.send(message);
        } catch (MessagingException e){
            e.printStackTrace();
            return false;
        }
        catch (java.lang.Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
